<template>
  <div class="repair-request-container">
    <div class="app-container">
      <el-card class="box-card">
        <div
          slot="header"
          class="clearfix"
        >
          <span v-if="!id">报修申请</span>
          <el-page-header
            v-else
            @back="goBack"
            content="修改报修申请"
          >
          </el-page-header>
        </div>

        <div class="from">
          <el-form
            :model="dataForm"
            :rules='dataRules'
            ref="dataForm"
            label-width="80px"
          >
            <el-form-item
              label="报修类型"
              prop='type_id'
              style="display: inline-block; margin-right: 20px"
            >
              <el-cascader
                placeholder="选择报修类型"
                v-model="dataForm.type_id"
                :options="repairTypeList"
                filterable
                style="width: 380px"
                :props="{label: 'name', value:'id', emitPath: false}"
              ></el-cascader>
            </el-form-item>
            <el-form-item
              label="报修区域"
              prop="a_id"
            >
              <el-select
                filterable
                clearable
                v-model="dataForm.a_id"
                placeholder="请选择报修区域"
                style="width: 150px"
              >
                <el-option
                  v-for="item in areaOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="联系电话"
              prop='phone'
              style="display: inline-block"
            >
              <el-input
                minlength="11"
                maxlength="11"
                placeholder="请输入联系电话"
                v-model.trim="dataForm.phone"
                clearable
                show-word-limit
                style="width: 300px"
                @keyup.enter.native="RepairRequestFn()"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              label="报修地点"
              prop='place'
            >
              <el-input
                minlength="3"
                maxlength="50"
                show-word-limit
                placeholder="请输入报修地点"
                v-model.trim="dataForm.place"
                clearable
                @keyup.enter.native="RepairRequestFn()"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              label="问题描述"
              prop='problem'
            >
              <el-input
                show-word-limit
                type="textarea"
                :rows="5"
                minlength="5"
                maxlength="200"
                placeholder="请输入问题描述"
                v-model.trim="dataForm.problem"
                clearable
                @keyup.enter.native="RepairRequestFn()"
              >
              </el-input>
            </el-form-item>

          </el-form>

          <div class="img-list">
            <div
              style="display: flex; flex-wrap:wrap;"
              v-if="dataForm.p_name"
            >
              <template v-for="(item, index) in dataForm.p_name">
                <span
                  v-if="item"
                  class="img-item"
                  :key="item"
                  @mouseenter="mouseenterFn(index)"
                  @mouseleave="mouseleaveFn(index)"
                >
                  <el-image
                    v-if="item"
                    :src="imgUrl + item"
                    fit="scale-down"
                    style="width: 148px; height: 148px"
                    @click="bigImg = imgUrl + item"
                  >
                  </el-image>
                  <div
                    class="mask"
                    style="display: none;"
                  >
                    <i
                      class="el-icon-delete"
                      @click="deleteImg(index)"
                    ></i>
                  </div>
                </span>
              </template>
              <upload-img-list
                class="imgList"
                ref="upload"
              />
            </div>
            <upload-img-list
              v-else
              class="imgList"
              ref="upload"
            />
          </div>

          <div class="btn">
            <el-button
              type="primary"
              @click="RepairRequestFn()"
            >{{id?'提交报修申请':'修改报修申请'}}</el-button>
          </div>
        </div>
      </el-card>

      <el-dialog
        v-if="!id &&bigImg"
        :show-close='false'
      >
        <img
          width="100%"
          :src="bigImg"
        >
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getRepairInfoAPI,
  getRepairTypeListAPI,
  repairRequestAPI,
  screenAreaListAPI,
  updateRepairRequestAPI
} from '@/api'
import { transTree, goBack, imgUrl, urlArr } from '@/utils'

export default {
  name: 'repairRequest',
  data () {
    return {
      id: this.$route.params.id,
      dataForm: {},
      dataRules: {
        phone: [
          { required: true, message: '联系电话不能为空', trigger: 'change' },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ],
        a_id: [
          { required: true, message: '报修区域不能为空', trigger: 'blur' },
          {
            length: '16',
            type: 'string',
            message: '报修区域格式有误',
            trigger: 'blur'
          }
        ],
        type_id: [
          { required: true, message: '报修类型不能为空', trigger: 'blur' },
          {
            length: '16',
            type: 'string',
            message: '报修类型格式有误',
            trigger: 'blur'
          }
        ],
        problem: [
          { required: true, message: '问题描述不能为空', trigger: 'blur' },
          {
            min: 5,
            max: 200,
            type: 'string',
            message: '问题描述要求5-200个字符',
            trigger: 'blur'
          }
        ],
        place: [
          { required: true, message: '报修地点不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 50,
            type: 'string',
            message: '报修地点要求3-50个字符',
            trigger: 'blur'
          }
        ],
        p_name: [
          {
            pattern: /(\S+,)*/,
            message: '图片格式有误',
            trigger: 'change'
          }
        ]
      },
      repairTypeList: [],
      imgUrl,
      bigImg: '',
      maskShow: false,
      areaOptions: {}
    }
  },
  created () {
    this.getRepairTypeListFn()
    this.getRepairInfoFn()
    this.getAreaFn()
  },
  methods: {
    // 获取报修类型列表
    async getRepairTypeListFn () {
      try {
        const { success, code, data } = await getRepairTypeListAPI()
        if (success && code === 10000) {
          this.repairTypeList = transTree(data, '')
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取维修区域 -> 发送请求
    async getAreaFn () {
      try {
        const { success, code, data } = await screenAreaListAPI({
          page: 1
        })
        if (success && code === 10000) {
          data.forEach((item) => {
            this.$set(this.areaOptions, item.id, {
              value: item.id,
              label: item.name
            })
          })
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取报修请求信息
    async getRepairInfoFn () {
      if (this.id) {
        try {
          const { success, code, data } = await getRepairInfoAPI(this.id)
          if (success && code === 10000) this.dataForm = urlArr(data)
        } catch (err) {
          return console.dir(err)
        }
      }
    },
    // 提交 | 修改报修申请 -> 点击事件 -> 发送请求
    async RepairRequestFn () {
      this.$refs.dataForm.validate(async (valid) => {
        try {
          if (valid) {
            const pName = await this.$refs.upload.submitUpload()
            if (this.dataForm.p_name) this.$set(this.dataForm, 'p_name', [...this.dataForm?.p_name, ...pName.split(',')])
            else this.$set(this.dataForm, 'p_name', pName.split(','))
            const { success, code } = !this.id
              ? await repairRequestAPI({
                ...this.dataForm,
                p_name: pName
              })
              : await updateRepairRequestAPI({
                ...this.dataForm,
                id: this.id,
                p_name: this.dataForm.p_name.join(',')
              })
            if (success && code === 10000) {
              if (!this.id) this.$router.push('/repair/underway')
            }
            this.getRepairInfoFn()
          }
        } catch (err) {
          this.$message.error(err.message)
          return console.dir(err)
        }
      })
    },
    goBack,
    // 删除图片
    deleteImg (index) {
      this.$set(this.dataForm.p_name, 'p_name', this.dataForm.p_name.splice(index, 1))
    },
    mouseenterFn (index) {
      document.querySelectorAll('.img-item')[index].querySelector('.mask').style.display = 'block'
    },
    mouseleaveFn (index) {
      document.querySelectorAll('.img-item')[index].querySelector('.mask').style.display = 'none'
    }
  }
}
</script>

<style lang="less" scoped>
.btn {
  margin-top: 20px;
  text-align: center;
}
.imgList {
  margin-left: 20px;
}
.box-card > div {
  padding: 30px;
}
.from {
  margin: 0 auto;
  max-width: 860px;
  min-width: 380px;
}
.img-list {
  display: flex;
}
.img-item {
  position: relative;
  top: 0;
  border-radius: 6px;
  overflow: hidden;
  font-size: 20px;
  width: 148px;
  height: 148px;
  transition: opacity 0.3s;
}
.mask {
  position: absolute;
  top: 0;
  text-align: center;
  line-height: 148px;
  width: 148px;
  height: 148px;
  background-color: rgba(0, 0, 0, 0.5);
}
.mask i {
  color: #fff;
}
</style>
